package com.icee.myth.manager.channelHandler;

import com.icee.myth.manager.ServerMessageQueue;
import com.icee.myth.manager.message.serverMessage.builder.ManagerMessageBuilder;
import com.icee.myth.utils.LogConsts;
import com.icee.myth.utils.MLogger;
import com.icee.myth.utils.StackTraceUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 服务器间通信，Deamon服务器发消息给Manager服务器的Handler
 * @author liuxianke
 */
public class DeamonToManagerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // Add Deamon channel connected message to message queue
        ServerMessageQueue.queue().offer(ManagerMessageBuilder.buildDeamonConnectMessage(ctx.channel()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // Add Deamon channel close message to message queue
        ServerMessageQueue.queue().offer(ManagerMessageBuilder.buildDeamonCloseMessage(ctx.channel()));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // TODO: 接收到从Deamon来的消息
        MLogger.getlogger().log(LogConsts.LOGTYPE_DEBUG, "Manager receive something from deamon.");
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        MLogger.getlogger().debuglog(LogConsts.LOGLEVEL_DEBUG, StackTraceUtil.getStackTrace(cause));
        ctx.channel().close();
    }

}
